/**
 * 
 */
package com.jxc.action.xsgl;

import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.BasicArgument;
import com.jxc.model.po.Fhtj;
import com.jxc.model.po.Goods;
import com.jxc.model.po.Member;
import com.jxc.model.po.MemberType;
import com.jxc.model.po.SaleDayTotal;
import com.jxc.model.po.Salelist;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VAuditRecord;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VGoodsRepertory;
import com.jxc.model.vo.VMember;
import com.jxc.model.vo.VMemberType;
import com.jxc.model.vo.VPointUsedRecord;
import com.jxc.model.vo.VRemindWarn;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VSaleReturnlist;
import com.jxc.model.vo.VSalelist;
import com.jxc.model.vo.VSalelistItem;
import com.jxc.model.vo.VTransferlist;
import com.jxc.model.vo.VUser;
import com.jxc.service.AuditRecordServiceI;
import com.jxc.service.BasicArgumentServiceI;
import com.jxc.service.GoodsRepertoryServiceI;
import com.jxc.service.GoodsServiceI;
import com.jxc.service.MemberServiceI;
import com.jxc.service.MemberTypeServiceI;
import com.jxc.service.PointUsedRecordServiceI;
import com.jxc.service.RemindWarnServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.SaleReturnlistServiceI;
import com.jxc.service.SalelistItemServiceI;
import com.jxc.service.SalelistServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.Constants;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author Tino
 * 
 */
@Namespace("/xsgl")
@Action(value = "salelistAction", results = { @Result(name = "saletotal", location = "/sale/saleTotal.jsp"),
												@Result(name = "saleRank", location = "/sale/saleRank.jsp"),
												@Result(name = "settlement", location = "/sale/settlement.jsp"),
												@Result(name = "settlementTotal", location = "/sale/settlementTotal.jsp"),
												@Result(name = "salelistItem", location = "/sale/salelistItem.jsp"),
												@Result(name="saledayTotal",location="/sale/saleDayTotal.jsp")})
public class SalelistAction extends BaseAction implements ModelDriven<VSalelist> {
	private final static Logger logger = Logger.getLogger(SalelistAction.class);

	private VSalelist model = new VSalelist();
	private String items;
	private String itemsforprint;
	private String mSerial;

	private VSalelistItem vsli = new VSalelistItem();
	
	@Autowired
	private SalelistServiceI salelistService;
	@Autowired
	private SalelistItemServiceI salelistItemService;
	@Autowired
	private PointUsedRecordServiceI pointUserRecordService;
	@Autowired
	private GoodsServiceI goodsService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private GoodsRepertoryServiceI goodsreService;
	@Autowired
	private RepertoryServiceI repertoryService;
	@Autowired
	private MemberServiceI memberService;
	@Autowired
	private MemberTypeServiceI memberTypeService;
	@Autowired
	private AuditRecordServiceI auditRecordService;
	@Autowired
	private SaleReturnlistServiceI saleReturnlistService;
	@Autowired
	private BasicArgumentServiceI basicArumentService;
	@Autowired
	private RemindWarnServiceI remindWarnService;
	@Autowired
	private BaseDaoI<Salelist> baseDao;
	private String mids;
	public String getMids() {
		return mids;
	}


	public VSalelistItem getVsli() {
		return vsli;
	}


	public void setVsli(VSalelistItem vsli) {
		this.vsli = vsli;
	}


	public void setMids(String mids) {
		this.mids = mids;
	}
	public void noAuth_datagrid() throws Exception {
		
		try { 
//			if (StringUtils.isNotBlank(mSerial)) {
//				VMember vm = new VMember();
//				vm.setSerial(mSerial);
//				vm.setMobile("");
//				List<VMember> vms = memberService.combobox(vm);
//				if (vms.size() > 0) {
//					model.setMid(vms.get(0).getId());
//				} else {
//					model.setMid(0l);
//				}
//			}
			model.setmSerial(mSerial);
			if (model.getBeginDate() != null) {
				String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
				model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
			}
			if (model.getEndDate() != null) {
				String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
				model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
			}
			if (model.getRid() != null) {
				this.writeJson(salelistService.datagrid(model));
			} else if(model.getUid()!=null){
				this.writeJson(salelistService.datagrid(model));
			}else {
				SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
				VUser vuser = userService.get(sessionInfo.getUserId());
				if (vuser.getReid() != null) {
					model.setRid(vuser.getReid());
					this.writeJson(salelistService.datagrid(model));
				} else {
					model.setUpid(vuser.getId());
					this.writeJson(salelistService.datagrid(model)); 
				}
			}	
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	


	//销售记录查询
	public void noAuth_datagridTotal() {
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest()
					.getSession().getAttribute(ResourceUtil.getSessionInfoName());
			
			VUser vuser = userService.get(sessionInfo.getUserId());
			model.setmSerial(mSerial.trim());
			if(vuser.getReid()!=null){
				model.setRid(vuser.getReid());
				this.writeJson(salelistService.findGather(model));
			}else{
				model.setUpid(sessionInfo.getUserId());
				this.writeJson(salelistService.findGather(model));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void noAuth_add() {
		logger.info("销售了一批商品!");
		Json j = new Json();
		try {
			model.setRemark(new URLDecoder().decode(model.getRemark(), "UTF-8"));
			/*
			 * ------------------------------------------------------------------
			 * ------------------------------ 保存销售单
			 * ------------------------------------------------------------------
			 */
			model.setDate(new Date());
			Long slId = salelistService.save(model);
 
			Map<Long, VSalelistItem> itemMap = new HashMap<Long, VSalelistItem>();
			List<VSalelistItem> vslis = new ArrayList<VSalelistItem>();
			Map<Long, VGoodsRepertory> vgMap = new HashMap<Long, VGoodsRepertory>();

			String[] itemArr = items.split(",");
			for (int i = 0; i < itemArr.length; i++) {
				Long gid = Long.parseLong(itemArr[i]);
				Double showPrice = Double.parseDouble(itemArr[++i]);
				Integer num = Integer.parseInt(itemArr[++i]);
				Double total = Double.parseDouble(itemArr[++i]);

				VSalelistItem vsli =  null;
					vsli = new VSalelistItem();
					vsli.setGid(gid);
					vsli.setSalePrice(showPrice);
					vsli.setNumber(num);
					vsli.setTotal(total);
					vslis.add(vsli);
					itemMap.put(gid, vsli);
					VGoodsRepertory vg = new VGoodsRepertory();
					vg.setOrid(model.getRid());
					String sLong = String.valueOf(vsli.getNumber()); 
					vg.setNum(Integer.parseInt(sLong));
					vg.setGid(vsli.getGid());
					goodsreService.findOut(vg);

			}

			/*
			 * ------------------------------------------------------------------
			 * ------------------------------ 保存销售单明细
			 * ------------------------------------------------------------------
			 */
			this.salelistItemService.batchSave(vslis, slId);
			
			/*
			 * ------------------------------------------------------------------
			 * ------------------------------ 处理打印数据
			 * ------------------------------------------------------------------
			 */
			String[] itemArrForPrint = items.split(",");
			List<VSalelistItem> vslisForPrint = new ArrayList<VSalelistItem>();
			
			for (int i = 0; i < itemArrForPrint.length; i++) {
				Long gid = Long.parseLong(itemArrForPrint[i]);
				Double showPrice = Double.parseDouble(itemArrForPrint[++i]);
				Integer num = Integer.parseInt(itemArrForPrint[++i]);
				Double total = Double.parseDouble(itemArrForPrint[++i]);
				VSalelistItem vsliForPrint =  new VSalelistItem();
				List<VGoods> list = new ArrayList<VGoods>();
				if(gid.toString()!=null){
					VGoods goodsmodel = new VGoods();
					goodsmodel.setRid(gid);
					list = goodsService.findForGoods(goodsmodel);
					VGoods vgoods = list.get(0);
					String tempbarcode = vgoods.getType();
					String tempname = vgoods.getName(); 
//					if(tempbarcode.length() > 8 ){
//						tempbarcode = tempbarcode.substring(0, 8);
//					}
					vsliForPrint.setGtype(tempbarcode);
					vsliForPrint.setGname(new URLDecoder().decode(tempname,"UTF-8"));
				}else{
					vsliForPrint.setGtype("00000000");
					vsliForPrint.setGname("no goods");
				}								
				vsliForPrint.setNumber(num);
				vsliForPrint.setTotal(total);
				vslisForPrint.add(vsliForPrint);
			}			
			this.getSession().setAttribute("Vsli", vslisForPrint);
			this.getSession().setAttribute("shouldPay", model.getTotal());
			this.getSession().setAttribute("saleserial",model.getSerial());
			this.getSession().setAttribute("realPay", model.getRealPay());
			this.getSession().setAttribute("charge", model.getCharge());
			logger.info(model.getUid());
			VUser vuserforprint = userService.get(model.getUid());
			this.getSession().setAttribute("salename", vuserforprint.getUsername());			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			this.getSession().setAttribute("saletime",sdf.format(model.getDate()));
			List<VRepertory> vrepertories = new ArrayList<VRepertory>();
			VRepertory vrepertory = new VRepertory();
			vrepertory.setId(model.getRid());
			vrepertories = repertoryService.list(vrepertory);
			if(vrepertories.size()>0){
				VRepertory vrep = vrepertories.get(0);
				this.getSession().setAttribute("ridname", vrep.getName());
				this.getSession().setAttribute("ridadd", vrep.getAddress());
				this.getSession().setAttribute("ridtel", vrep.getPhone());
			}else{
				this.getSession().setAttribute("ridname", "");
				this.getSession().setAttribute("ridadd", "");
				this.getSession().setAttribute("ridtel", "");
			}
			

			/*
			 * ------------------------------------------------------------------
			 * 客户使用了积分来支付，扣除会员使用积分，增加消费金额和消费积分，记录积分使用记录
			 * ------------------------------------------------------------------
			 */
			
			int moneyPointProp = 1;
			int pointMoneyProp = 1;
			if(model.getUid()!=null){
				if((model.getUid()==3||model.getUid()==4)&&userService.get(model.getId()).getUpid()!=null){
					if(userService.get(userService.get(model.getId()).getUpid()).getMoneyPointProp()!=null){
						moneyPointProp = userService.get(userService.get(model.getId()).getUpid()).getMoneyPointProp();
					}
					if(userService.get(userService.get(model.getId()).getUpid()).getPointMoneyProp()!=null){
						pointMoneyProp = userService.get(userService.get(model.getId()).getUpid()).getPointMoneyProp();
					}					
				}else{
					if(userService.get(model.getUid())!=null){
						if(userService.get(model.getUid()).getMoneyPointProp()!=null){
							moneyPointProp = userService.get(model.getUid()).getMoneyPointProp();
						}
						if(userService.get(model.getUid()).getPointMoneyProp()!=null){
							pointMoneyProp = userService.get(model.getUid()).getPointMoneyProp();
						}
					}
				}
			}
			
			if (model.getMid() != null) {
				System.out.println(model.getMid());
				VMember param = new VMember();
				param.setId(model.getMid());
				List<VMember> vms = memberService.combobox(param);
				VMember vm = vms.get(0);
				
				Double consume = (model.getRealPay() * 100 - model.getCharge() * 100) / 100;
				if(vm.getConsume()!=null){
					vm.setConsume(vm.getConsume() + consume);
				}else{
					vm.setConsume(consume);
				}
				
				//更新会员积分
				if(vm.getPoint()!= null&& model.getPointNum()!=null){
					vm.setPoint(vm.getPoint() - model.getPointNum());
				}
				if(vm.getPoint()!= null){
					vm.setPoint(vm.getPoint() + (int) Math.floor(consume/moneyPointProp));
				}else{
					vm.setPoint((int) Math.floor(consume));
				}
				
				//会员升级功能 start
				if(vm.getMemberType()!=null&&vm.getMemberType().getMaxAmount()!=null&&vm.getConsume()>vm.getMemberType().getMaxAmount()){
					SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
					VUser vuser = userService.get(sessionInfo.getUserId());
					VMemberType vmt = new VMemberType();
					if(vuser.getUserType()==1||vuser.getUserType()==5){
						vmt.setUid(vuser.getId());
					}
					if(vuser.getUpid()!=null&&(vuser.getUserType()==3||vuser.getUserType()==4)&&(userService.get(vuser.getUpid()).getUserType()==1||userService.get(vuser.getUpid()).getUserType()==5)){
						vmt.setUid(vuser.getUpid());
					}
					List<VMemberType> vmts = memberTypeService.combobox(vmt);
					for(VMemberType vmt1 : vmts){
						if(vmt1.getMinAmount()!=null&&vm.getConsume()>vmt1.getMinAmount()){
							if(vmt1.getMaxAmount()!=null){
								if(vm.getConsume()<vmt1.getMaxAmount()){
									MemberType mt = new MemberType();
									BeanUtils.copyProperties(vmt1, mt);
									vm.setMemberType(mt);
								}
							}else{
								MemberType mt = new MemberType();
								BeanUtils.copyProperties(vmt1, mt);
								vm.setMemberType(mt);
							}
						}
					}
				}
				//会员升级功能 end
				
				memberService.update(vm);

				//添加积分使用记录
				if (model.getPointNum() > 0) {
					VPointUsedRecord vpur = new VPointUsedRecord();
					vpur.setDate(model.getDate());
					vpur.setNum(model.getPointNum());
					vpur.setMid(model.getMid());
					vpur.setSlid(slId);
					this.pointUserRecordService.save(vpur);
				}
				
				/*
				 * --------------------------------------------------------------------------------------
				 * 会员积分提醒
				 * --------------------------------------------------------------------------------------
				 */
//				BasicArgument ba = this.basicArumentService.getBasricArgumentByKey(model.getRid(), Constants.MIN_POINT_REMIND);
//				if (vm.getPoint() > Integer.parseInt(ba.getArgValue())) {
//					VRemindWarn vrw = new VRemindWarn();
//					vrw.setTime(new Date());
//					vrw.setContent("会员[姓名：" + vm.getName() + "，编号：" + vm.getSerial() + "]积分已经达到" + vm.getPoint() + "，请提醒他/她来消费！");
//					vrw.setIsDone(false);
//					vrw.setUid(vm.getUid());
//					this.remindWarnService.save(vrw);
//				}
			}
			j.setObj(slId);
			j.setMsg("销售成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("销售失败！");
			logger.info(ExceptionUtil.getExceptionMessage(e));
			e.printStackTrace();
		}
		super.writeJson(j);
	}

	//日清结算 保存数据
	public void noAuth_settlement() {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());

		Json j = new Json();
		j.setMsg("统计成功！");
		VAuditRecord ar = new VAuditRecord();
		try {
			ar.setBeginAudit(model.getBeginDate());
			ar.setEndAudit(model.getEndDate());
			ar.setRid(model.getRid());
			ar.setUid(vuser.getId());

			Double total = 0.0;

			if (model.getBeginDate() != null) {
				String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
				model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
			}

			VAuditRecord param = new VAuditRecord();
			param.setRid(model.getRid());
			param.setOrder("desc");
			param.setSort("endAudit");
			List<VAuditRecord> vars = auditRecordService.combobox(param);
			if (vars.size() > 0) {
				VAuditRecord var = vars.get(0);
				this.getRequest().setAttribute("EndAudit", new SimpleDateFormat("yyyy年MM月dd日").format(var.getEndAudit()));
				Calendar cal = Calendar.getInstance();
				cal.setTime(var.getEndAudit());
				cal.add(Calendar.DAY_OF_MONTH, 1);
				Date systemBeginDate = cal.getTime();

				if (model.getBeginDate() == null) {
					j.setMsg("结算开始时间不能为空！");
					super.writeJson(j);
					return;
				}

				if (systemBeginDate.after(model.getBeginDate())) {
					j.setMsg("结算开始时间早于或等于上次结算时间！");
					super.writeJson(j);
					return;
				}
			}

			if (model.getEndDate() != null) {
				String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
				model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
			}

			if (model.getEndDate().before(model.getBeginDate())) {
				j.setMsg("结算结束时间早于结算开始时间！");
				super.writeJson(j);
				return;
			}

			VSalelist para = new VSalelist();
			para.setRid(model.getRid());
			para.setBeginDate(model.getBeginDate());
			para.setEndDate(model.getEndDate());
			List<VSalelist> vsls = salelistService.combobox(para);
			if (vsls.size() > 0) {
				for (VSalelist vsl : vsls) {
					if (vsl.getPointNum() == null) {
						total += vsl.getTotal();
					} else {
						BasicArgument ba = this.basicArumentService.getBasricArgumentByKey(model.getRid(), Constants.INTEGRAL_CONVERSION_RATIO);
						Double point=0d;
						
						if(vsl!=null&&ba!=null){
							point = (vsl.getPointNum() / Double.parseDouble(ba.getArgValue()));
						}
						
						if (point < vsl.getTotal()) {
							total += (vsl.getTotal() - point);
						}
					}
				}

				VSaleReturnlist par = new VSaleReturnlist();
				par.setRid(model.getRid());
				par.setBeginDate(model.getBeginDate());
				para.setEndDate(model.getEndDate());
				List<VSaleReturnlist> vsrls = saleReturnlistService.combobox(par);
				if (vsrls.size() > 0) {
					for (VSaleReturnlist vsrl : vsrls) {
						total -= vsrl.getRealReturn();
					}
				}

				DecimalFormat format = new DecimalFormat("0.00");
				total = Double.parseDouble(format.format(total));
			}

			ar.setTotal(total);
			auditRecordService.save(ar);
		} catch (Exception e) {
			logger.info(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("统计异常！");
		}
		
	
		super.writeJson(j);
	}

	@Override
	public VSalelist getModel() {
		return model;
	}

	public void noAuth_checkSalelist() {
		DataGrid dataGrid = salelistService.datagridNoPage(model);

		Json json = new Json();
		if (dataGrid.getRows() != null && dataGrid.getRows().size() > 0) {
			writeJson(dataGrid.getRows());
		} else {
			json.setSuccess(false);
			json.setMsg("没有该销售单!");
			writeJson(json);
		}
	}

	public void noAuth_checkItems() {
		writeJson(salelistService.getItems(model));
	}

	public String getItems() {
		return items;
	}

	public void setItems(String items) {
		this.items = items;
	}

	public String getItemsforprint() {
		return itemsforprint;
	}


	public void setItemsforprint(String itemsforprint) {
		this.itemsforprint = itemsforprint;
	}


	public String getMSerial() {
		return mSerial;
	}

	public void setMSerial(String serial) {
		mSerial = serial;
	}

	/*
	 * --------------------------------------------------------------------------------------
	 * 营业员销售统计
	 * --------------------------------------------------------------------------------------
	 */

	//日銷售分析
	public String saledayTotal(){
		getSubAuths("SALE_DAY");
		return "saledayTotal";
	}
	
	/**
	 * 日销售统计图表
	 */
	public void saleDayTotalImage(){
		
		//获取仓库 begin
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());
		List<VRepertory> vrepertories = new ArrayList<VRepertory>();
		if (vuser.getReid() != null) {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setId(vuser.getReid());
			vrepertories = repertoryService.list(vrepertory);
		}else {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setUid(sessionInfo.getUserId());
			vrepertories = repertoryService.list(vrepertory);
		}
		

		
		//产生图表
		try{
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("image/jpeg");
			JFreeChart chart = salelistService.saleDayTotalJFreeChat(vrepertories, model, vuser);;
			ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, 945, 240);
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	//日销售分析
	public void saledayTotalDatagrid(){
		
		//将查询条件存放到session
		//条件 rid = begin
//		HttpSession session=ServletActionContext.getRequest().getSession();
//		session.setAttribute("model", model);
		
		
		//获取仓库 begin
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());
		List<VRepertory> vrepertories = new ArrayList<VRepertory>();
		if (vuser.getReid() != null) {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setId(vuser.getReid());
			vrepertories = repertoryService.list(vrepertory);
		}else {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setUid(sessionInfo.getUserId());
			vrepertories = repertoryService.list(vrepertory);
		}
		//仓库获取end
		DataGrid dg=salelistService.datagridDayTotal(vrepertories, model, vuser);
		if(dg.getTotal()<=0){
			this.writeJson(dg);
		}
		//拼接字符串
		/*
		 {"d1":12,"num":13,"rname":"万寿路店"}
		 * */
		String json="{\"rows\":[";
		for(Object obj:dg.getRows()){
			SaleDayTotal dayTotal=(SaleDayTotal)obj;
			String content="{";
			content+="\"num\":"+dayTotal.getNum()+",";
			content+="\"rname\":"+"\""+dayTotal.getRname()+"\",";
			content+="\"sumMoney\":"+String.format("%.1f" ,dayTotal.getSumMoney())+",";
			content+="\"profits\":"+String.format("%.1f" ,dayTotal.getProfits())+",";
			for(int i=0;i<dayTotal.getDays().length;i++){
				
				content+="\"d"+(i+1)+"\":"+dayTotal.getDays()[i]+",";
				
			}
			content=content.substring(0, content.length()-1);
			content+="}";
			json+=content+",";
		}
		json=json.substring(0, json.length()-1);
		json+="],\"total\":"+dg.getTotal()+"}";
		
		try{
			ServletActionContext.getResponse().setContentType(
			"text/html;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(json);
			ServletActionContext.getResponse().getWriter().flush();
			ServletActionContext.getResponse().getWriter().close();
		}catch (Exception e) {
			e.printStackTrace();
		}	
		
	}
	
	
	public String saleTotal() {
		getSubAuths("SJTJ_XSTJ");
		return "saletotal";
	}
	
	public String settlement() {
		getSubAuths("XSGL_RQJS");
		return "settlement";
	}
	
	public String saleRank() {
		getSubAuths("SJTJ_SPXSPH");
		return "saleRank";
	}
		
	public void edit(){	
		try {
			salelistService.editModel(model);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void findSaleDetail(){
		try {
			this.writeJson(salelistService.findSaleDetail(model));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取销售统计数据后返回datagrid给页面
	 * @throws Exception
	 */
	public void datagridTotal() throws Exception {
		DataGrid dg = new DataGrid();
		dg.setTotal(0l);
		dg.setRows(new ArrayList<VSalelist>());
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());	
		model.setUpid(vuser.getUpid());
//
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
//		SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-01");
//		if (model.getBeginDate() != null) {
//			String beginDateStr = sd.format(model.getBeginDate());
//			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
//		}
//		else{
//			String beginDateStr = sd1.format(new Date());
//			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
//		}
//		if (model.getEndDate() != null) {
//			String endDateStr = sd.format(model.getEndDate());
//			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
//		}else{
//			String endDateStr = sd.format(new Date());
//			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
//		}
		
		if (vuser.getReid() != null) {
			model.setRid(vuser.getReid());
		}
		
		if(model.getGroupby()==null||model.getGroupby().trim().equals("")||model.getGroupby().trim().equals("null")){
			model.setGroupby("user");
		}
		
		if(model.getOrder()==null||model.getOrder().trim().equals("")||model.getOrder().trim().equals("null")){
			model.setOrder("total");
		}
		dg=salelistService.datagridTotal(model);
		this.writeJson(dg);
	}
	
	/**
	 * 获取销售排行数据后返回datagrid给页面
	 * @throws Exception
	 */
	public void datagridRank() throws Exception {
		DataGrid dg = new DataGrid();
		dg.setTotal(0l);
		dg.setRows(new ArrayList<VSalelist>());
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());	
		model.setUpid(vuser.getUpid());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-01");
		if (model.getBeginDate() != null) {
			String beginDateStr = sd.format(model.getBeginDate());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}else{
			String beginDateStr = sd1.format(new Date());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = sd.format(model.getEndDate());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}else{
			String endDateStr = sd.format(new Date());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}
		
		if (vuser.getReid() != null) {
			model.setRid(vuser.getReid());
		}
		
		if(model.getGroupby()==null||model.getGroupby().trim().equals("")||model.getGroupby().trim().equals("null")){
			model.setGroupby("user");
		}
		
		if(model.getOrder()==null||model.getOrder().trim().equals("")||model.getOrder().trim().equals("null")){
			model.setOrder("total");
		}
		dg=salelistService.datagridRank(model);
		this.writeJson(dg);
	}
	
	/**
	 * 获取销售统计数据后返回统计图给页面
	 * @return
	 * @throws Exception
	 */
	public String saleTotalChart() throws Exception {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());	
		model.setUpid(vuser.getUpid());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-01");
		if (model.getBeginDate() != null) {
			String beginDateStr = sd.format(model.getBeginDate());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}else{
			String beginDateStr = sd1.format(new Date());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = sd.format(model.getEndDate());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}else{
			String endDateStr = sd.format(new Date());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}
		
		if (vuser.getReid() != null) {
			model.setRid(vuser.getReid());
		}
		
		if(model.getGroupby()==null||model.getGroupby().trim().equals("")||model.getGroupby().trim().equals("null")){
			model.setGroupby("user");
		}
		
		if(model.getOrder()==null||model.getOrder().trim().equals("")||model.getOrder().trim().equals("null")){
			model.setOrder("total");
		}
		
		
		List<Object[]> vsls = salelistService.saleTotal(model);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("image/jpeg");
		JFreeChart chart = salelistService.getSaleTotalChart(vsls,model);
		ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, 315, 240);
		
		return null;
	}
	
	/**
	 * 获取销售排行数据后返回统计图给前端
	 * @return
	 * @throws Exception
	 */
	public String saleRankChart() throws Exception {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());	
		model.setUpid(vuser.getUpid());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-01");
		if (model.getBeginDate() != null) {
			String beginDateStr = sd.format(model.getBeginDate());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}else{
			String beginDateStr = sd1.format(new Date());
			model.setBeginDate(sdf.parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = sd.format(model.getEndDate());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}else{
			String endDateStr = sd.format(new Date());
			model.setEndDate(sdf.parse(endDateStr + " 23:59:59"));
		}
		
		if (vuser.getReid() != null) {
			model.setRid(vuser.getReid());
		}
		
		if(model.getGroupby()==null||model.getGroupby().trim().equals("")||model.getGroupby().trim().equals("null")){
			model.setGroupby("brand");
		}
		
		if(model.getOrder()==null||model.getOrder().trim().equals("")||model.getOrder().trim().equals("null")){
			model.setOrder("total");
		}
		
		List<Object[]> vsls = salelistService.saleRank(model);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("image/jpeg");
		JFreeChart chart = salelistService.getSaleRankChart(vsls,model);
		ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, 945, 240);
		
		return null;
	}
	
	
	/*
	 * --------------------------------------------------------------------------------------
	 * 对账明细统计
	 * --------------------------------------------------------------------------------------
	 */
	
	public String settlementTotal() {
		getSubAuths("SJTJ_DZMX");
		return "settlementTotal";
	}
	
	//获取结算数据
	public void datagridsettlementTotal() throws Exception {
		if (model.getBeginDate() != null) {
			String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}else{
			String beginDateStr = new SimpleDateFormat("yyyy-MM-01").format(new Date());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}else{
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}
		if (model.getRid() != null) {
			this.writeJson(salelistService.datagridsettlementTotal(model));
		}else{
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());		
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(salelistService.datagridsettlementTotal(model));

			}else if(vuser.getUserType()!=null&&(vuser.getUserType()==1||vuser.getUserType()==2||vuser.getUserType()==5)){
				model.setUpid(vuser.getId());
				this.writeJson(salelistService.datagridsettlementTotal(model));

			}else{
				DataGrid dg = new DataGrid();
				dg.setTotal(0l);
				dg.setRows(new ArrayList<VSalelist>());
				this.writeJson(dg);
			}
						
		}
		
	}

	/*
	 * --------------------------------------------------------------------------------------
	 * 销售明细查询
	 * --------------------------------------------------------------------------------------
	 */
	
	public String salelistItem(){
		getSubAuths("XSGL_XSMXCX");
		return "salelistItem";
	}
	
	public void noAuth_salelistItemDatagrid(){
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.
					getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());	
//			sysou
			if(vuser.getReid()!= null){
				DataGrid dg = new DataGrid();
				vsli.setGcolor(model.getGcolor());
				vsli.setPage(model.getPage());
				vsli.setRows(model.getRows());
				vsli.setGtid(model.getGtid());
				vsli.setGtype(model.getGtype());
				vsli.setGsize(model.getGsize());
				vsli.setGbarcode(model.getGbarcode());
				vsli.setBid(model.getBid());
				vsli.setRid(vuser.getReid());
				vsli.setOrder(model.getOrder());
				vsli.setSort(model.getSort()); 
				vsli.setBeginDate(model.getBeginDate());
				vsli.setEndDate(model.getEndDate());
				dg = salelistItemService.datagridAll(vsli);
				this.writeJson(dg);
			}else{
				DataGrid dg = new DataGrid();
				vsli.setUid(sessionInfo.getUserId());
				vsli.setPage(model.getPage());
				vsli.setRows(model.getRows());
				vsli.setGtid(model.getGtid());
				vsli.setGtype(model.getGtype());
				vsli.setGsize(model.getGsize());
				vsli.setGbarcode(model.getGbarcode());
				vsli.setBid(model.getBid());
				vsli.setRid(model.getRid());
				vsli.setOrder(model.getOrder());
				vsli.setSort(model.getSort());
				vsli.setGcolor(model.getGcolor());
				vsli.setBeginDate(model.getBeginDate());
				vsli.setEndDate(model.getEndDate());
				dg = salelistItemService.datagridAll(vsli);
				this.writeJson(dg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void noAuth_saleTotal(){
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.
					getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());	
			if(vuser.getReid()!=null){
				vsli.setRid(vuser.getReid());
				vsli.setPage(model.getPage());
				vsli.setRows(model.getRows());
				vsli.setGtid(model.getGtid());
				vsli.setGtype(model.getGtype());
				vsli.setGsize(model.getGsize());
				vsli.setGbarcode(model.getGbarcode());
				vsli.setBid(model.getBid());
				vsli.setGcolor(model.getGcolor());
				vsli.setBeginDate(model.getBeginDate());
				vsli.setEndDate(model.getEndDate());
				this.writeJson(salelistItemService.findSaleTotal(vsli));
			}else{
				vsli.setPage(model.getPage());
				vsli.setRows(model.getRows());
				vsli.setGtid(model.getGtid());
				vsli.setGtype(model.getGtype());
				vsli.setGsize(model.getGsize());
				vsli.setGbarcode(model.getGbarcode());
				vsli.setBid(model.getBid());
				vsli.setRid(model.getRid());
				vsli.setUid(vuser.getId());
				vsli.setGcolor(model.getGcolor());
				vsli.setBeginDate(model.getBeginDate());
				vsli.setEndDate(model.getEndDate());
				VSalelistItem vs = salelistItemService.findSaleTotal(vsli);
				this.writeJson(vs);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
//打印
	public void noAuth_print(){
		try {
			this.writeJson(salelistService.findSaleDetail(model));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		/*try {
			Salelist  vs = baseDao.get(Salelist.class, model.getId()); 
			ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write("这是打印页面");
			ServletActionContext.getResponse().getWriter().flush();
			ServletActionContext.getResponse().getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}*/
	}

}
